package view;
import date.GameData;
import date.GameRule;
import date.Music;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class MainFrame extends JFrame {
    JButton button1 = null; // 创建第一个点击按钮对象
  JButton button2 = null;
final GameData gameData = new GameData();
    private JLabel scoreLabel;
    private int score = 0;
    private Music music;

    JButton[][] buttons = new JButton[GameData.rows][GameData.cols];
    final int width=600;
    final int height=600;
    private JLabel timeLabel;
    private  int seconds = 0;
    private Timer timer;
    public MainFrame() {
        music = new Music("Music/bgm.wav");
        music.playLoop();

        Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        this.setTitle("动物连连看");


        this.setBounds(1, 1, width, height);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setLocation((screenSize.width - width) / 2, (screenSize.height - height) / 2);

        JMenuBar menubar = new JMenuBar();
        this.setJMenuBar(menubar); // 设置菜单栏
        JMenu menu1 = new JMenu("文件");
        JMenuItem mi1 = new JMenuItem("重新开始");
        JMenuItem mi3 = new JMenuItem("退出");
        menubar.add(menu1); // 添加菜单栏
        menu1.add(mi1);
        menu1.add(mi3);
        // 为菜单项添加事件监听器
        mi1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("重新开始");
            }
        });
        mi3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("退出");
            }
        });
        initPane();
        initButton();
        showImage();
        startTimer();

    }


    @Override
    public void dispose() {
        if (music != null) {
            music.stop();
        }
        super.dispose();
        music.stop();
    }

    private void initPane() {
            JPanel scorePane = new JPanel(new FlowLayout()); // 设置成流体布局
            scorePane.add(new JLabel("用户名：link"));
            scorePane.add(new JLabel("    "));

            scoreLabel = new JLabel("得分：" + score);
            scorePane.add(scoreLabel);
            timeLabel = new JLabel("时间0秒");
            scorePane.add(timeLabel);

            JButton btnResort = new JButton("重排");
            JButton btnReplay = new JButton("新游戏");
            btnResort.setContentAreaFilled(false);
            btnResort.setBorderPainted(false);
        btnResort.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("重排");
                gameData.shuffleData();
                showImage();
            }
        });


        // 对"新游戏"按钮添加监听事件
        btnReplay.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("新游戏");
                setVisible(false);
                new MainFrame().setVisible(true);
                dispose();  // 释放此窗口的资源
            }
        });
            scorePane.add(btnResort);
            scorePane.add(btnReplay);
            this.getContentPane().add(scorePane, BorderLayout.NORTH); // 添加此在面板上面

        }
    private void startTimer() {
        // 每秒触发一次事件
        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                seconds++;
                timeLabel.setText("时间：" + seconds + " 秒");
                // 检查游戏是否结束
                if (isGameOver()) {
                    timer.stop();
                    JOptionPane.showMessageDialog(MainFrame.this, "游戏结束！得分：" + score + "，用时：" + seconds + " 秒");
                }
            }
        });
        timer.start();
    }


    public void initButton() {
        JPanel gamePanel = new JPanel(new GridLayout(GameData.rows, GameData.cols)); // 设置成网格布局
        for (int i = 0; i < GameData.rows; ++i)
            for (int j = 0; j < GameData.cols; ++j) {
                buttons[i][j] = new JButton(); // 生成按钮

                // 对每个按钮设置监听事件
                buttons[i][j].addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // 判断哪个按钮被点击
                        JButton button = (JButton) e.getSource();
                        // 如果button1 没有记录，即点击第一个按钮
                        if (button1 == null) {
                            button1 = button; // 记录第一个按钮
                            button1.setBackground(Color.BLUE); // 记录第一个按钮的底色为蓝色
                        } else {
                            // 否则，如果点击的是第二个按钮，则两个按钮都隐藏
                            button2 = button; // 记录第二个按钮
                            button2.setBackground(Color.BLUE); // 记录第二个按钮的底色为蓝色
                            // 记录第一个按钮的行数
                            int row1 = (button1.getY() / button1.getHeight()) + 1;
                            // 记录第一个按钮的列数
                            int col1 = (button1.getX() / button1.getWidth()) + 1;
                            // 记录第二个按钮的行数
                            int row2 = (button2.getY() / button2.getHeight()) + 1;
                            // 记录第二个按钮的列数
                            int col2 = (button2.getX() / button2.getWidth()) + 1;
                            // 输出两个按钮的位置 以及 相应的data值
                            System.out.println(row1 + " " + col1);
                            System.out.println(row2 + " " + col2);
                            // 判断两个图案是否能够相连
                            // 遍历输出二维数组的值
                            for (int k = 0; k < GameData.rows + 2; ++k) {
                                for (int l = 0; l < GameData.cols + 2; ++l) {
                                    System.out.print(gameData.data[k][l] + " ");
                                }
                                System.out.println();
                            }
                            if(GameRule.isConnect(gameData.data, row1, col1, row2, col2)){
                                // 隐藏两个按钮
                                button1.setVisible(false);
                                button2.setVisible(false);
                                gameData.data[row1][col1] = 0;
                                gameData.data[row2][col2] = 0;
                                score+=10;
                                scoreLabel.setText("得分：" + score);
                            }
                            //检查是否结束
                            if (isGameOver()) {
                                timer.stop();
                                JOptionPane.showMessageDialog(MainFrame.this, "游戏结束！得分：" + score + "，用时：" + seconds + " 秒");
                            }
                            // 还原两个按钮为空
                            button1.setBackground(Color.WHITE);
                            button2.setBackground(Color.WHITE);
                            button1 = null;
                            button2 = null;

                        }
                    }
                });

                gamePanel.add(buttons[i][j]);
                // 居中显示
                this.getContentPane().add(gamePanel, BorderLayout.CENTER);
            }
         }
        private boolean isGameOver() {
            for (int i = 1; i <= GameData.rows; ++i) {
                for (int j = 1; j <= GameData.cols; ++j) {
                    if (gameData.data[i][j] != 0) {
                        return false;
                    }
                }
            }
            return true;
        }
        private void showImage(){
            for (int i = 0; i < GameData.rows; ++i) {
                for (int j = 0; j < GameData.cols; ++j) {
                    buttons[i][j].setVisible(true);
//                String path = this.getClass().getResource("/image").getPath();
                    // 获取图片路径
                    ImageIcon icon = new ImageIcon("src/images/" + gameData.data[i + 1][j + 1] + ".png");
//                System.out.println(icon);
                    // 设置图片大小
                    icon.setImage(icon.getImage().getScaledInstance(
                            60, 60,
                            Image.SCALE_DEFAULT));
                    buttons[i][j].setIcon(icon);
                }
            }
        }

}

